//
//  THUserBabyHomeViewController.m
//  TreeHole
//
//  Created by apple on 2020/9/22.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THUserBabyHomeViewController.h"
#import "THBabyUserHomeTableViewCell.h"
#import "THMajorUserViewController.h"
#import "THBabyMineOrderViewController.h"
#import "THUserBabySearchViewController.h"
@interface THUserBabyHomeViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */
@property(nonatomic, strong) STTools_SegementAutoView                     *segView;/**<  */
@property(nonatomic, strong) UITextField                     *searchTextFiled;/**<  */
@property(nonatomic, strong) NSMutableArray                     *banner;/**<  */
@end

@implementation THUserBabyHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self) weakSelf =  self;
    self.tableView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, 300, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"暂无数据" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf stoneobs_fun_st_send_list_request];
    }];
    [self.tableView.mj_header beginRefreshing];
    [self stoneobs_ui_configSubView];
    [self configTableHeader];

    
    // Do any additional setup after loading the view.
}
#pragma mark --configSubView
- (void)stoneobs_ui_configSubView{
    __weak typeof(self) weakSelf =  self;
    self.segView = [[STTools_SegementAutoView alloc] initWithFrame:CGRectMake(20, 0, UISCREEN_WIDTH * 0.5, 44) andTitle:@[@"附近",@"关注"] handle:^(STTools_SegementAutoView *sender, UIButton *currentSelctedButton) {
        
        [weakSelf.tableView.mj_header beginRefreshing];
    }];
    self.segView.lineSelectedColor = UIColor.clearColor;
    self.segView.lineSelectedView.backgroundColor = UIColor.clearColor;
    self.segView.lineColor = UIColor.clearColor;
    self.segView.autoMoveWithClic = YES;
    
    self.segView.butTitleSelectedColor = UIColor.whiteColor;
    self.segView.butTitleColor = STONEOBS_UI_THIRD_TEXT_COLOR;
    self.segView.butTitleFont = [UIFont systemFontOfSize:15];
    self.segView.butTitleSelectedFont = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:17];
    
    UIImageView * stoneobs_ui_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 21, 10)];
    stoneobs_ui_imageView.image = [UIImage imageNamed:@"椭圆4"];
    [self.segView.lineSelectedView addSubview:stoneobs_ui_imageView];
    stoneobs_ui_imageView.centerX = self.segView.lineSelectedView.width/2;
    stoneobs_ui_imageView.centerY =  self.segView.lineSelectedView.height / 2;
    self.segView.lineSelectedView.clipsToBounds = NO;
    self.segView.lineSelectedView.top = self.segView.lineSelectedView.top-5;
    self.segView.clipsToBounds = NO;
    self.segView.buttonBackGroundColor = UIColor.clearColor;
    self.segView.buttonSelctedBackGroundColor = UIColor.clearColor;
    self.segView.backgroundColor = UIColor.clearColor;
    
    self.cus_navgationBar.backgroundColor = UIColor.clearColor;
//    [self.cus_navgationBar addSubview:self.segView];
    [self.cus_navgationBar.titleButton setTitle:@"育婴师" forState:UIControlStateNormal];
    [self.cus_navgationBar.titleButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    
    self.segView.centerX = UISCREEN_WIDTH / 2;
    self.segView.bottom = TMUtils.stoneobs_fun_get_navgationBarBootom;
    
    [self.cus_navgationBar.rightButton setTitle:@"我的订单" forState:UIControlStateNormal];
    [self.cus_navgationBar.rightButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [self.cus_navgationBar.rightButton setClicAction:^(UIButton *sender) {
        [weakSelf pushViewController:THBabyMineOrderViewController.new animated:1];
    }];

    UIView * topVIew = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_navgationBarBootom+100)];
    [self.view insertSubview:topVIew atIndex:0];
    topVIew.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:topVIew.bounds andColors:@[WH_UICOLOR_FROM_RGBA(0x4AD941),WH_UICOLOR_FROM_RGBA(0x37CF34),UIColor.whiteColor]];
    topVIew.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:topVIew.bounds andColors:@[FlatYellow,FlatOrange,UIColor.whiteColor]];
    
    UIColor * stoneobs_ui_buttonBgColor1 = [UIColor colorWithRed:217/255.0 green:141/255.0 blue:131/255.0 alpha:1];
    UIColor * stoneobs_ui_buttonBgColor2 = [UIColor colorWithRed:255/255.0 green:214/255.0 blue:223/255.0 alpha:1];
    topVIew.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:topVIew.bounds andColors:@[stoneobs_ui_buttonBgColor1,stoneobs_ui_buttonBgColor2,UIColor.whiteColor]];
    
    self.tableView.backgroundColor = UIColor.clearColor;
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.frame = CGRectMake(0, topVIew.bottom - 40, UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_tabBarTop+49 - (topVIew.bottom - 40));
    
    
    UITextField * textFiled = [[UITextField alloc] initWithFrame:CGRectMake(15, TMUtils.stoneobs_fun_get_navgationBarBootom+15, UISCREEN_WIDTH- 30, 32)];
    textFiled.backgroundColor = UIColor.whiteColor;
    textFiled.layer.cornerRadius = 16;
    textFiled.clipsToBounds = YES;
    textFiled.placeholder = @"请输入关键字";
    textFiled.delegate = self;
    textFiled.clearButtonMode = UITextFieldViewModeAlways;
    textFiled.returnKeyType = UIReturnKeySearch;
    self.searchTextFiled = textFiled;
    
    textFiled.userInteractionEnabled = NO;
    STButton * gobutton = [[STButton alloc] initWithFrame:textFiled.frame
                                                              title:nil
                                                         titleColor:nil
                                                          titleFont:0
                                                       cornerRadius:0
                                                    backgroundColor:nil
                                                    backgroundImage:nil
                                                              image:nil];
    
    [topVIew addSubview:gobutton];
    [gobutton setClicAction:^(UIButton *sender) {
        [weakSelf pushViewController:THUserBabySearchViewController.new animated:1];
    }];
    
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)
                                                              title:@""
                                                         titleColor:STONEOBS_UI_THIRD_TEXT_COLOR
                                                          titleFont:12
                                                       cornerRadius:16
                                                    backgroundColor:nil
                                                    backgroundImage:nil
                                                              image:ST_IMAGE_NAMED(@"搜索")];
    stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [textFiled stoneobs_fun_setstoneobs_fun_st_leftView:stoneobs_ui_button];
    
    [topVIew addSubview:textFiled];
}
- (void)configTableHeader{
    UIView * header = [UIView.alloc initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
    __weak typeof(self) weakSelf =  self;
    [THHomeDataController stoneobs_fun_get_banner_request_cid:@"8" num:10 handle:^(NSArray * _Nonnull banner) {
        
        STTools_PageView * page_view = [[STTools_PageView alloc] initWithFrame:CGRectMake(10, 10, STONEOBS_UI_UISCREEN_WIDTH - 20, 160)];
        //        page_view.imageArray = @[STFDRandomImageProvider.random_banner_shop_image,
        //                                 STFDRandomImageProvider.random_banner_shop_image,
        //                                 STFDRandomImageProvider.random_banner_shop_image,
        //                                 STFDRandomImageProvider.random_banner_shop_image
        //        ].mutableCopy;
        page_view.imageUrlArray = [[banner stoneobs_fun_arrayFromObjKeyName:@"obj.img"] mutableCopy];
        page_view.animationType = FSPagerViewTransformerTypeNone;
        [page_view setOnSelectedBannerHandle:^(NSInteger index) {
            
            THBannerModel * model = banner[index];
            [TMUtils auto_deal_banner:model];
        }];
        page_view.backgroundColor = UIColor.clearColor;
        [header addSubview:page_view];
        
        page_view.pagerView.layer.cornerRadius = 4;
        page_view.pagerView.clipsToBounds = YES;
        page_view.autoMoveDuring = 4;
        
        STPageControl * pageControl = [STPageControl.alloc initWithPages:page_view.imageUrlArray.count handle:^(NSInteger tag) {
            
        }];
        pageControl.currentPageIndicatorTintColor  = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
        pageControl.pageIndicatorTintColor = [STONEOBS_UI_THEME_BACKGROUNDCOLOR colorWithAlphaComponent:0.3];
        pageControl.centerX = STONEOBS_UI_UISCREEN_WIDTH / 2;
        pageControl.bottom = page_view.bottom - 35;
        [header addSubview:pageControl];
        __weak typeof(pageControl) weakpageControl=  pageControl;
        [page_view setScrollDidScroll:^(NSInteger currentIndex) {
            weakpageControl.currentPage = currentIndex;
        }];
        
    }];
    
    
    
    header.height = 170 - 30 + 15;
    self.tableView.tableHeaderView = header;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self.tableView.mj_header beginRefreshing];
        [self.searchTextFiled resignFirstResponder];
    }
    return YES;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return THBabyUserHomeTableViewCell.stoneobs_ui_cell_height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    THBabyUserHomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[THBabyUserHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    THMajorUserModel * model = self.dataSouce[indexPath.row];
    cell.model = model;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    THMajorUserModel * model = self.dataSouce[indexPath.row];
    THMajorUserViewController * vc = THMajorUserViewController.new;
    vc.userModel = model;
    [self pushViewController:vc animated:1];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --stoneobs_net netWork Method
- (void)configRefreshFooter{
    __weak typeof(self) weakSelf =  self;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf stoneobs_fun_st_send_list_request];
    }];
}
- (void)stoneobs_fun_st_send_list_request{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.searchTextFiled.text.length) {
        [stoneobs_net_param_dic setObject:self.searchTextFiled.text forKey:@"keywords"];
        [stoneobs_net_param_dic setObject:self.searchTextFiled.text forKey:@"keyword"];
    }
    [stoneobs_net_param_dic setObject:@(self.page) forKey:@"page"];
    //http://bf.xingzhuosong.com//v1/goods/goodsList?name=%E8%92%9C%E8%8B%97&page=1
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/nursery/index"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        //        CGFloat total = [[responseObject valueForKey:@"data"][@"total"] floatValue];
        //        CGFloat perPage = [[responseObject valueForKey:@"data"][@"perPage"] floatValue];;//每一页数据
        //        total = ceil(total/perPage);//总共多少页
        CGFloat total =  1;
        NSArray * array = [responseObject valueForKey:@"data"];
        NSArray * objArry = [THMajorUserModel mj_objectArrayWithKeyValuesArray:array];
        if (self.page == 1) {
            self.dataSouce = NSMutableArray.new;
            [self.tableView.mj_header endRefreshing];
            if (total > self.page) {
                [self configRefreshFooter];
            }
        }else{
            if (total > self.page) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.dataSouce addObjectsFromArray:objArry];
        [self.tableView reloadData];
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        if (self.page > 1) {
            self.page --;
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
    
}
@end
